package com.jzoom.zoom.admin.controllers;

import com.jzoom.zoom.admin.models.FileExplorerService;
import com.jzoom.zoom.caster.codec.Base64;
import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.web.annotations.*;
import com.jzoom.zoom.web.exception.StatusException;
import com.jzoom.zoom.web.view.View;
import com.jzoom.zoom.web.view.impl.FileView;
import com.jzoom.zoom.web.view.impl.StringView;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller(key="file")
public class FieExplorerController implements AdminController {


    @Inject
    private FileExplorerService explorerService;


    @JsonResponse
    public List<FileExplorerService.FileInfo> list(String path, String filter) {

        return explorerService.getInfo(path, filter);
    }

    @Mapping("download/{path}")
    public View download(@Param(pathVariable = true) String path) {
        path = new String(Base64.decodeFast(path));
        File file = new File(path);
        return new FileView(file);
    }


    /**
     * 加载文件内容
     *
     * @return
     */
    public View content(
            @Param(comment = "文件名") @Required String name,
            @Param(comment = "文件夹") @Required String dir
    ) {
        try {
            return new StringView(explorerService.getContent(new File(dir, name)));
        } catch (IOException e) {
            throw new StatusException.ApiError("文件读取错误");
        }

    }

    @JsonResponse
    public void save(
            @Param(comment = "文件名") @Required String name,
            @Param(comment = "文件夹") @Required String dir,
            String value
    ) {
        try {
            explorerService.saveContent(new File(dir, name), value);
        } catch (IOException e) {
            throw new StatusException.ApiError("文件写入错误");
        }

    }
}
